import { useState, useRef, useEffect } from 'react'
import { message, Button, Input, Slider, Switch, Card, Tabs, Badge } from 'antd'
import { useTranslation } from 'react-i18next'
import { 
  AudioOutlined, 

  SendOutlined, 

  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  SoundOutlined,

  ExperimentOutlined
} from '@ant-design/icons'
import img1 from '../../assets/image/speeching.gif'
import userAvatar from '../../assets/imgs/1.png'
import aiAvatar from '../../assets/imgs/2.png'
import SparkVoiceRecognition from '../../utils/sparkVoiceRecognition'
import XunfeiTTS from '../../utils/xunfeiTTS'
import XunfeiSpark from '../../utils/xunfeiSpark'
import { useNavigate } from 'react-router-dom'

import TestRunner from '../../components/TestRunner'
import VoiceRecognitionPanel from '../../components/VoiceRecognitionPanel'
import TTSDebugger from '../../components/TTSDebugger'
import type { SparkVoiceConfig, VoiceRecognitionResult, VoiceRecognitionStats } from '../../utils/sparkVoiceRecognition'
import type { TTSConfig } from '../../utils/xunfeiTTS'
import { useSpeechStore } from '../../store/speechStore'
import { globalAudioAnalyzer } from '../../utils/audioAnalyzer'
import type { AudioAnalysisData } from '../../store/speechStore'

interface Tupi3Props {
  onToggleChat?: () => void
}

interface ChatMessage {
  id: string
  type: 'user' | 'ai' | 'voice-recognition'
  content: string
  timestamp: number
  avatar?: string
  isVoiceMessage?: boolean
  isRealtime?: boolean
  isFinal?: boolean
}

// 动画状态接口
interface AnimationState {
  isIdle: boolean
  isSpeaking: boolean
  isListening: boolean
  isThinking: boolean
  emotion: 'happy' | 'neutral' | 'excited' | 'focused'
  eyeBlinkRate: number
  headMovement: boolean
}



function Tupi3(_props: Tupi3Props) {
  const { t: i18nT, i18n } = useTranslation();
  // 全局语音状态管理
  const { setSpeaking, setPlaying, setCurrentText, setAudioData, setCharacterAction } = useSpeechStore()
  const navigate = useNavigate()
  
  const [chatBoxShown, setChatBoxShown] = useState(false)
  const [inputText, setInputText] = useState('')
  const [isRecognizing, setIsRecognizing] = useState(false)
  const [recognizedText, setRecognizedText] = useState('')
  const [isSupported, setIsSupported] = useState(false)
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [currentVoiceMessage, setCurrentVoiceMessage] = useState<ChatMessage | null>(null)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  // 文字转语音相关状态
  const [isPlaying, setIsPlaying] = useState(false)
  const [isSynthesizing, setIsSynthesizing] = useState(false)
  const [voiceVolume, setVoiceVolume] = useState(90)
  const [voiceSpeed, setVoiceSpeed] = useState(60)
  const [voicePitch, setVoicePitch] = useState(50)
  const t = useRef<number | null>(null)
  const [voiceTimeout, setVoiceTimeout] = useState(2000) // 可配置的超时时间

  // 动画控制状态
  const [animationState, setAnimationState] = useState<AnimationState>({
    isIdle: true,
    isSpeaking: false,
    isListening: false,
    isThinking: false,
    emotion: 'neutral',
    eyeBlinkRate: 3,
    headMovement: true
  })
  
  // 控制面板显示状态
  const [showControlPanel, setShowControlPanel] = useState(false)
  const [autoVoiceReply, setAutoVoiceReply] = useState(true)
  const [continuousListening, setContinuousListening] = useState(false)
  
  // 语音识别性能监控状态
  const [voiceStats, setVoiceStats] = useState<VoiceRecognitionStats>({
    totalAttempts: 0,
    successCount: 0,
    errorCount: 0,
    averageResponseTime: 0,
    accuracy: 0
  })
  const [currentAudioData, setCurrentAudioData] = useState<Float32Array>()
  const [showVoicePanel, setShowVoicePanel] = useState(false)
  const [showTestPanel, setShowTestPanel] = useState(false)
  const [showTTSDebugger, setShowTTSDebugger] = useState(false)
  
  const voiceRecognitionRef = useRef<SparkVoiceRecognition | null>(null)
  const ttsRef = useRef<XunfeiTTS | null>(null)
  const sparkService = useRef<XunfeiSpark | null>(null)
  const audioRef = useRef<HTMLAudioElement | null>(null)
  const lastSendTimeRef = useRef<number>(0)
  const lastActionRef = useRef<'idle' | 'run' | 'happy' | 'sad' | null>(null)
  const lastActionTsRef = useRef<number>(0)
  // 防止重复跳转的标记
  const hasNavigatedRef = useRef<boolean>(false)
  // 防止重复语言切换的标记
  const hasLanguageSwitchedRef = useRef<boolean>(false)
  // 防止重复主题切换的标记
  const hasThemeSwitchedRef = useRef<boolean>(false)
  
  // 组件挂载时同步本地持久化的主题
  useEffect(() => {
    try {
      const savedTheme = localStorage.getItem('theme')
      if (savedTheme === 'gray' || savedTheme === 'zinc') {
        document.documentElement.setAttribute('data-theme', savedTheme)
      }
    } catch {}
  }, [])
  
  // 自动滚动到最新消息
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 添加语音识别消息到聊天区域
  const addVoiceMessage = (text: string, isFinal: boolean = false) => {
    const voiceMessageId = 'voice-recognition-current'
    
    if (!currentVoiceMessage) {
      // 创建新的语音识别消息
      const newVoiceMessage: ChatMessage = {
        id: voiceMessageId,
        type: 'voice-recognition',
        content: text,
        timestamp: Date.now(),
        avatar: userAvatar,
        isVoiceMessage: true,
        isRealtime: !isFinal,
        isFinal: isFinal
      }
      
      setCurrentVoiceMessage(newVoiceMessage)
      setMessages(prev => [...prev, newVoiceMessage])
    } else {
      // 更新现有的语音识别消息
      const updatedMessage: ChatMessage = {
        ...currentVoiceMessage,
        content: text,
        timestamp: Date.now(),
        isRealtime: !isFinal,
        isFinal: isFinal
      }
      
      setCurrentVoiceMessage(updatedMessage)
      setMessages(prev => 
        prev.map(msg => 
          msg.id === voiceMessageId ? updatedMessage : msg
        )
      )
    }
    
    // 如果是最终结果，清空当前语音消息状态
    if (isFinal) {
      setTimeout(() => {
        setCurrentVoiceMessage(null)
      }, 100)
    }
    
    // 自动滚动到最新消息
    setTimeout(scrollToBottom, 50)
  }

  // 清除当前语音识别消息
  const clearVoiceMessage = () => {
    if (currentVoiceMessage) {
      setMessages(prev => prev.filter(msg => msg.id !== currentVoiceMessage.id))
      setCurrentVoiceMessage(null)
    }
  }

  useEffect(() => {
    // 星火语音识别配置
    const sparkVoiceConfig: SparkVoiceConfig = {
      appId: import.meta.env.VITE_XUNFEI_APP_ID || 'ad822389',
      apiKey: import.meta.env.VITE_XUNFEI_API_KEY || '0e9cb05f9a2d597ac10b81bea6d05eb4',
      apiSecret: import.meta.env.VITE_XUNFEI_API_SECRET || 'MDAyZTBhYjMzYTFiOTJhZDFhODBjNjBh'
    }

    // 添加配置验证和调试信息
    console.log('星火语音识别API配置检查:')
    console.log('- APP_ID:', sparkVoiceConfig.appId ? '已配置' : '未配置')
    console.log('- API_KEY:', sparkVoiceConfig.apiKey ? '已配置' : '未配置')
    console.log('- API_SECRET:', sparkVoiceConfig.apiSecret ? '已配置' : '未配置')
    
    // 验证配置完整性
    if (!sparkVoiceConfig.appId || !sparkVoiceConfig.apiKey || !sparkVoiceConfig.apiSecret) {
      console.error('星火语音识别API配置不完整！')
      message.error(i18nT('tupi3.errors.configIncomplete'))
      return
    }

    const ttsConfig: TTSConfig = {
      appId: sparkVoiceConfig.appId,
      apiKey: sparkVoiceConfig.apiKey,
      apiSecret: sparkVoiceConfig.apiSecret
    }

    // 检查浏览器支持
    setIsSupported(SparkVoiceRecognition.isSupported())
    
    // 初始化语音识别和TTS服务
    console.log('初始化星火语音识别服务...')
    voiceRecognitionRef.current = new SparkVoiceRecognition(sparkVoiceConfig, (audioData: Float32Array) => {
      // 音频数据回调，用于实时波形显示
      setCurrentAudioData(audioData)
    })
    ttsRef.current = new XunfeiTTS(ttsConfig)
    let time = 0 // 用于记录语音识别结果长度的变量
      // 设置识别结果回调
      voiceRecognitionRef.current.onResult = (result: VoiceRecognitionResult) => {
        console.log('语音识别结果:', result)
        const currentTime = result.text?.length || 0
      
      // 清除之前的定时器
      if (t.current) {
        clearTimeout(t.current)
        console.log('清除之前的定时器')
      }
      
      // 设置新的定时器
      t.current = setTimeout(() => {
        generateAIResponse(result.text)
        try {
          console.log(`定时器触发: 当前长度=${currentTime}, 结果长度=${result.text?.length || 0}`)
          
          // 检查语音识别是否已经停止或结果长度没有变化
          if (result.text && result.text.length > 0 && result.text.length === currentTime) {
            console.log('语音识别超时，自动停止')
            stopVoiceRecognition()
            setIsRecognizing(false)
            
            // 显示超时提示
            message.info(i18nT('tupi3.info.recognitionTimeout'))
          }
        } catch (error) {
          console.error('定时器执行出错:', error)
          // 确保在出错时也能停止识别
          stopVoiceRecognition()
          setIsRecognizing(false)
        }
      }, voiceTimeout)
      
      if (result.text) {
        // 主题切换：识别到主题指令立即切换（含非最终结果，防重入）
        const themeTarget = mapTextToTheme(result.text || '')
        console.log('[主题匹配]', { text: result.text, themeTarget, isFinal: result.isFinal })
        if (!hasThemeSwitchedRef.current && themeTarget) {
          hasThemeSwitchedRef.current = true
          try {
            document.documentElement.setAttribute('data-theme', themeTarget)
            try { localStorage.setItem('theme', themeTarget) } catch {}
            const tip = themeTarget === 'zinc' ? (i18nT?.('theme.night') || '已切换为夜晚模式') : (i18nT?.('theme.day') || '已切换为白天模式')
            try { message.success(String(tip)) } catch {}
          } catch (e) {
            console.error('主题切换失败:', e)
            try { message.error('主题切换失败') } catch {}
          }
          clearVoiceMessage()
          setIsRecognizing(false)
          try { stopVoiceRecognition() } catch {}
          return
        }
        // 语言切换：识别到语言指令立即切换（含非最终结果，防重入）
        const langTarget = mapTextToLanguage(result.text || '')
        console.log('[语言匹配]', { text: result.text, langTarget, current: i18n.language, isFinal: result.isFinal })
        if (!hasLanguageSwitchedRef.current && langTarget) {
          hasLanguageSwitchedRef.current = true
          try {
            i18n.changeLanguage(langTarget)
              .then(() => {
                const tip = langTarget === 'zh' ? '已切换为中文' : 'Switched to English'
                try { message.success(tip) } catch {}
              })
              .catch((e) => {
                console.error('语言切换失败:', e)
                try { message.error('语言切换失败') } catch {}
              })
          } catch (e) {
            console.error('语言切换调用异常:', e)
          }
          clearVoiceMessage()
          setIsRecognizing(false)
          try { stopVoiceRecognition() } catch {}
          return
        }

        // 语音导航：识别到导航指令即跳转（含非最终结果，防重入）
        const navPath = mapTextToNavigation(result.text || '')
        console.log('[导航匹配]', { text: result.text, navPath, isFinal: result.isFinal })
        if (!hasNavigatedRef.current && navPath) {
          hasNavigatedRef.current = true
          try {
            const tip = navPath === '/sd'
              ? '正在为您打开3D展览馆'
              : navPath === '/login'
              ? '正在为您打开登录页'
              : navPath === '/ai-chat'
              ? '正在为您打开AI聊天'
              : '正在为您返回首页'
            message.info(tip)
          } catch {}
          clearVoiceMessage()
          setIsRecognizing(false)
          try { stopVoiceRecognition() } catch {}
          navigate(navPath)
          return
        }
        // 解析动作指令并触发数字人动作
        const action = mapTextToAction(result.text)
        if (action) {
          // 防抖与去重：避免高频识别结果导致重复更新
          const prev = useSpeechStore.getState().characterAction
          const now = Date.now()
          const tooSoon = now - lastActionTsRef.current < 300
          const isSame = prev === action || lastActionRef.current === action
          if (!tooSoon && !isSame) {
            setCharacterAction(action)
            lastActionRef.current = action
            lastActionTsRef.current = now
            try {
              message.info(`已切换动作: ${action}`)
            } catch {}
          }
        }
        // 将语音识别结果直接渲染到聊天消息区域
        addVoiceMessage(result.text, result.isFinal)
        
        // 更新动画状态 - 正在听取
        setAnimationState(prev => ({
          ...prev,
          isListening: true,
          isIdle: false,
          emotion: 'focused'
        }))
        
        if (result.isFinal) {
          console.log('语音识别完成，将通过AI处理:', result.text)
          
          // 将最终的语音识别结果转换为用户消息，并通过AI处理
          setTimeout(() => {
            // 清除语音识别消息
            clearVoiceMessage()
           
            // 添加用户消息到聊天记录
            const userMessage: ChatMessage = {
              id: Date.now().toString(),
              type: 'user',
              content: result.text,
              timestamp: Date.now(),
              avatar: userAvatar
            }
            setMessages(prev => [...prev, userMessage])
            
            // 自动滚动到最新消息
            setTimeout(scrollToBottom, 100)
            
            // 通过AI生成智能回复（而不是直接回复）
            setTimeout(() => {
              generateAIResponse(result.text)
            }, 50)
            
          }, 100) // 减少延迟到100ms，提供更快的响应
          
          // 重置动画状态
          setAnimationState(prev => ({
            ...prev,
            isListening: false,
            isThinking: true,
            emotion: 'neutral'
          }))
          
          // 停止语音识别
          setIsRecognizing(false)
          
          // 如果开启了连续监听，在AI回复完成后自动重新开始语音识别
          if (continuousListening) {
            setTimeout(() => {
              if (!isRecognizing) {
                console.log('连续监听模式，等待AI回复完成后重新开始语音识别')
                startVoiceRecognition()
              }
            }, 2000) // 增加延迟到2秒，等待AI回复完成
          }
        }
      }
    }

    // 设置错误回调
    voiceRecognitionRef.current.onError = (error: string) => {
      console.error('语音识别错误:', error)
      
      // 根据错误类型提供不同的友好提示
      let errorMessage = i18nT('tupi3.errors.recognitionGeneric')
      let errorType = 'error'
      
      if (error.includes('麦克风') || error.includes('microphone')) {
        errorMessage = i18nT('tupi3.errors.micAccess')
        errorType = 'warning'
      } else if (error.includes('网络') || error.includes('network')) {
        errorMessage = i18nT('tupi3.errors.networkIssue')
        errorType = 'warning'
      } else if (error.includes('超时') || error.includes('timeout')) {
        errorMessage = i18nT('tupi3.errors.recognitionTimeout')
        errorType = 'info'
      } else if (error.includes('权限') || error.includes('permission')) {
        errorMessage = i18nT('tupi3.errors.permissionDenied')
        errorType = 'warning'
      } else if (error.includes('不支持') || error.includes('not supported')) {
        errorMessage = i18nT('tupi3.errors.browserNotSupported')
        errorType = 'error'
      }
      
      // 显示友好的错误提示
      if (errorType === 'error') {
        message.error(errorMessage)
      } else if (errorType === 'warning') {
        message.warning(errorMessage)
      } else {
        message.info(errorMessage)
      }
      
      // 重置状态
      setIsRecognizing(false)
      setRecognizedText('')
      setInputText('')
      
      // 重置动画状态
      setAnimationState(prev => ({
        ...prev,
        isListening: false,
        isIdle: true,
        emotion: 'neutral'
      }))
      
      // 更新统计信息
      setVoiceStats(prev => ({
        ...prev,
        errorCount: prev.errorCount + 1,
        lastError: error
      }))
    }
    
    // 初始化星火大模型
    sparkService.current = new XunfeiSpark({
      appId: sparkVoiceConfig.appId,
      apiKey: sparkVoiceConfig.apiKey,
      apiSecret: sparkVoiceConfig.apiSecret,
      domain: 'generalv3.5' // Spark Max版本
    })
    
    console.log('星火语音识别服务初始化完成')
    
    return () => {
      if (voiceRecognitionRef.current) {
        voiceRecognitionRef.current.stopRecognition()
      }
      sparkService.current?.close()
    }
  }, [])

  // 将中文指令映射为动作键值
  const mapTextToAction = (text: string): 'idle' | 'run' | 'happy' | 'sad' | null => {
    const s = text.toLowerCase()
    // 停止/空闲
    if (/(停止|站立|空闲|休息|idle)/.test(s)) return 'idle'
    // 跑步/运动
    if (/(跑步|奔跑|运动|快跑|run)/.test(s)) return 'run'
    // 开心挥手
    if (/(开心|高兴|挥手|打招呼|happy)/.test(s)) return 'happy'
    // 沮丧低落
    if (/(沮丧|低落|难过|sad)/.test(s)) return 'sad'
    return null
  }

  // 将中文/英文指令映射为页面导航
  const mapTextToNavigation = (text: string): string | null => {
    const s = text.toLowerCase()
    // 中文：进入/打开 3D 展览馆/大厅/展览
    if (/(进入|进|打开)\s*(3d)?\s*(展览馆|展览|馆|大厅)/.test(s)) return '/sd'
    // 中文：进入登录页/登录页面
    if (/(进入|打开|去)\s*(登录|登陆)(页|页面)?/.test(s)) return '/login'
    // 中文：进入AI聊天
    if (/(进入|打开|去)\s*ai\s*聊天/.test(s)) return '/ai-chat'
    // 中文：返回首页/主页
    if (/(返回|回到|进入|打开)\s*(首页|主页|home)/.test(s)) return '/'
    // 英文：enter/open 3D hall/exhibition
    if (/(enter|open)\s*3d\s*(hall|exhibition)/.test(s)) return '/sd'
    // 英文：login page
    if (/(enter|open|go to)\s*(login|sign in)(\s*page)?/.test(s)) return '/login'
    // 英文：AI chat
    if (/(enter|open|go to)\s*ai\s*chat/.test(s)) return '/ai-chat'
    // 英文：home
    if (/(go home|go to home|open home|enter home)/.test(s)) return '/'
    return null
  }

  // 将语音文本映射为语言切换指令
  const mapTextToLanguage = (text: string): 'zh' | 'en' | null => {
    const s = text.toLowerCase()
    // 直接切换到中文
    if (/(切换|转换|换成|改为|使用|说|speak|switch|change)\s*(中文|zh|chinese)/.test(s)) return 'zh'
    // 直接切换到英文
    if (/(切换|转换|换成|改为|使用|说|speak|switch|change)\s*(英文|en|english)/.test(s)) return 'en'
    // 在一个短句中表达"切换中英文"
    if (/(切换中英文|中英文切换|switch\s*language|switch\s*(between)?\s*(chinese|english))/i.test(s)) {
      return i18n.language === 'zh' ? 'en' : 'zh'
    }
    return null
  }
  
  // 将语音文本映射为主题切换指令（gray=白天，zinc=黑夜）
  const mapTextToTheme = (text: string): 'gray' | 'zinc' | null => {
    const s = text.toLowerCase()
    // 中文：切换到夜晚/黑夜/暗色/深色/黑色模式
    if (/(切换|转换|换成|改为|使用|打开|进入)\s*(夜晚|黑夜|暗色|深色|黑色)(模式|主题)?/.test(s)) return 'zinc'
    // 中文：切换到白天/日间/浅色/亮色/白色模式
    if (/(切换|转换|换成|改为|使用|打开|进入)\s*(白天|日间|浅色|亮色|白色)(模式|主题)?/.test(s)) return 'gray'
    // 中文：切换主题（未说明方向则在 gray/zinc 间切换）
    if (/(切换主题|主题切换|切换夜晚白天|切换白天夜晚)/.test(s)) {
      const cur = document.documentElement.getAttribute('data-theme')
      return cur === 'zinc' ? 'gray' : 'zinc'
    }
    // 英文：switch to dark/night theme
    if (/(switch|change|set)\s*(to)?\s*(dark|night)\s*(mode|theme)?/.test(s)) return 'zinc'
    // 英文：switch to light/day theme
    if (/(switch|change|set)\s*(to)?\s*(light|day)\s*(mode|theme)?/.test(s)) return 'gray'
    // 英文：toggle theme（未说明方向则在 gray/zinc 间切换）
    if (/(toggle|switch)\s*(theme|mode)/.test(s)) {
      const cur = document.documentElement.getAttribute('data-theme')
      return cur === 'zinc' ? 'gray' : 'zinc'
    }
    return null
  }

  // 开始语音识别
  const startVoiceRecognition = async () => {
    if (!voiceRecognitionRef.current) {
      message.error(i18nT('tupi3.errors.recognitionNotInitialized'))
      return
    }

    try {
      console.log('开始启动星火语音识别...')
      // 每次开始识别时允许新的导航
      hasNavigatedRef.current = false
      
      // 立即更新UI状态，提供即时反馈
      setIsRecognizing(true)
      setRecognizedText('')
      
      // 更新动画状态 - 开始监听
      setAnimationState(prev => ({
        ...prev,
        isListening: true,
        isIdle: false,
        isSpeaking: false,
        emotion: 'focused'
      }))
      
      // 异步启动语音识别，避免阻塞UI
      const startPromise = voiceRecognitionRef.current.startRecognition()
      
      // 使用Promise.race来设置超时，避免长时间等待
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('启动超时')), 5000)
      })
      
      await Promise.race([startPromise, timeoutPromise])
      console.log('星火语音识别启动成功')
      
      // 更新性能统计
      setVoiceStats(voiceRecognitionRef.current.getStats())
    } catch (error) {
      console.error('启动星火语音识别失败:', error)
      
      // 根据错误类型提供友好的错误提示
      let errorMessage = i18nT('tupi3.errors.recognitionStartFailed')
      const errorStr = String(error)
      
      if (errorStr.includes('启动超时')) {
        errorMessage = i18nT('tupi3.errors.startTimeout')
      } else if (errorStr.includes('麦克风') || errorStr.includes('microphone') || errorStr.includes('MediaDevices')) {
        errorMessage = i18nT('tupi3.errors.micAccess')
      } else if (errorStr.includes('网络') || errorStr.includes('network') || errorStr.includes('WebSocket')) {
        errorMessage = i18nT('tupi3.errors.networkFailed')
      } else if (errorStr.includes('配置') || errorStr.includes('config') || errorStr.includes('key')) {
        errorMessage = i18nT('tupi3.errors.configError')
      } else if (errorStr.includes('浏览器') || errorStr.includes('browser') || errorStr.includes('not supported')) {
        errorMessage = i18nT('tupi3.errors.browserNotSupportedChrome')
      }
      
      message.error(errorMessage)
      setIsRecognizing(false)
      setRecognizedText('')
      setInputText('')
      
      // 重置动画状态
      setAnimationState(prev => ({
        ...prev,
        isListening: false,
        isIdle: true,
        emotion: 'neutral'
      }))
      
      // 更新统计信息
      setVoiceStats(prev => ({
        ...prev,
        errorCount: prev.errorCount + 1,
        lastError: errorStr
      }))
    }
  }

  // 停止语音识别
  const stopVoiceRecognition = () => {
    if (voiceRecognitionRef.current) {
      voiceRecognitionRef.current.stopRecognition()
      setIsRecognizing(false)
      // 停止识别后重置导航标记，避免下一次无法跳转
      hasNavigatedRef.current = false
      // 停止识别后重置语言标记，避免下一次无法切换
      hasLanguageSwitchedRef.current = false
      // 停止识别后重置主题标记，避免下一次无法切换
      hasThemeSwitchedRef.current = false
      message.info(i18nT('tupi3.info.recognitionStopped'))
      
      // 重置动画状态
      setAnimationState(prev => ({
        ...prev,
        isListening: false,
        isIdle: true,
        emotion: 'neutral'
      }))
      
      // 更新性能统计
      setVoiceStats(voiceRecognitionRef.current.getStats())
    }
  }

  // 文字转语音功能 - 使用动态参数
  const textToSpeech = async (text: string) => {
    if (!ttsRef.current) {
      console.error('TTS服务未初始化')
      return
    }

    // 如果正在播放其他音频，先停止
    if (isPlaying) {
      stopPlaying()
    }

    try {
      setIsSynthesizing(true)
      
      // 更新动画状态 - 开始说话
      setAnimationState(prev => ({
        ...prev,
        isSpeaking: true,
        isIdle: false,
        isThinking: false,
        emotion: 'happy'
      }))
      
      // 更新全局语音状态
      setSpeaking(true)
      setCurrentText(text)
      
      console.log('开始语音合成:', text)
      
      const audioData = await ttsRef.current.synthesize(text, {
        voice: 'xiaoyan',
        speed: voiceSpeed,
        volume: voiceVolume,
        pitch: voicePitch
      })
      
      // 将PCM转换为WAV格式
      const wavData = ttsRef.current.pcmToWav(audioData)
      const audioBlob = new Blob([wavData], { type: 'audio/wav' })
      const audioUrl = URL.createObjectURL(audioBlob)
      
      // 立即播放音频
      if (audioRef.current) {
        audioRef.current.src = audioUrl
        await audioRef.current.play()
        setIsPlaying(true)
        setPlaying(true) // 更新全局播放状态
        console.log('语音播报开始')
      }
    } catch (error) {
      console.error('语音合成失败:', error)
      // 重置动画状态
      setAnimationState(prev => ({
        ...prev,
        isSpeaking: false,
        isIdle: true,
        emotion: 'neutral'
      }))
      
      // 重置全局语音状态
      setSpeaking(false)
      setCurrentText('')
    } finally {
      setIsSynthesizing(false)
    }
  }

  // 停止播放
  const stopPlaying = () => {
    if (audioRef.current) {
      audioRef.current.pause()
      audioRef.current.currentTime = 0
      setIsPlaying(false)
      setPlaying(false) // 更新全局播放状态
      
      // 重置动画状态
      setAnimationState(prev => ({
        ...prev,
        isSpeaking: false,
        isIdle: true,
        emotion: 'neutral'
      }))
      
      // 重置全局语音状态
      setSpeaking(false)
      setCurrentText('')
      setAudioData(null)
      
      // 停止音频分析
      globalAudioAnalyzer.stopAnalysis()
    }
  }

  // 发送消息
  const sendMessage = (text?: string) => {
    const messageText = text || inputText.trim()
    if (!messageText) return

    // 防抖处理，避免重复发送
    if (Date.now() - lastSendTimeRef.current < 500) {
      return
    }
    lastSendTimeRef.current = Date.now()

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      type: 'user',
      content: messageText,
      timestamp: Date.now(),
      avatar: userAvatar
    }

    setMessages(prev => [...prev, userMessage])
    setInputText('')
    
    // 自动滚动到最新消息
    setTimeout(scrollToBottom, 100)
    
    // 异步生成AI回复，避免阻塞UI
    setTimeout(() => {
      generateAIResponse(messageText)
    }, 50) // 减少延迟到50ms，提供更快的AI响应
  }

  // 生成AI回复
  const systemPrompt = `你是智能语音助手小维。请严格按照以下要求回复：

1. 智能分析用户问题，针对不同类型问题提供具体信息和建议：
   - 天气问题：提供具体天气信息和穿衣建议
   - 时间问题：提供准确时间和相关提醒
   - 生活问题：给出实用的生活建议和解决方案
   - 学习问题：提供学习方法和知识要点
   - 专业问题：给出专业性建议和相关资源

2. 回复风格要求：
   - 语气自然友好，适当使用emoji表情 😊
   - 回复长度控制在100字以内
   - 提供有价值的具体信息，不说空话套话

3. 严格禁止：
   - 不能说"我不知道"或类似模糊回复
   - 不能给出无用的通用回答
   - 必须针对具体问题给出有针对性的回复

请始终提供智能、友好、实用、全面的回答。`
  const generateAIResponse = async (userMessage: string): Promise<void> => {
    try {
      // 更新动画状态 - 思考中
      setAnimationState(prev => ({
        ...prev,
        isThinking: true,
        isIdle: false,
        emotion: 'focused'
      }))
      
      if (!sparkService.current) {
        const errorMessage = i18nT('tupi3.errors.aiServiceUnavailable')
        const aiMessage: ChatMessage = {
          id: Date.now().toString() + '_ai',
          type: 'ai',
          content: errorMessage,
          timestamp: Date.now(),
          avatar: aiAvatar
        }
        setMessages(prev => [...prev, aiMessage])
        
        // 自动播报服务不可用消息
        if (autoVoiceReply) {
          textToSpeech(errorMessage)
        }
        return
      }

      // 使用星火大模型生成回复
     
      
      console.log('开始调用星火大模型...')
      console.log('用户消息:', userMessage)
      console.log('系统提示:', systemPrompt)
      
      const response = await sparkService.current.sendMessage(
        userMessage,
        systemPrompt,
        (content, isComplete) => {
          // 实时显示AI回复
          console.log('AI实时回复:', content, '完成状态:', isComplete)
        },
        (error) => {
          console.error('星火大模型错误:', error)
      message.error(i18nT('tupi3.errors.aiReplyFailed') + ': ' + error)
        }
      )
      
      console.log('星火大模型响应完成:', response)

      const aiResponse = response || i18nT('tupi3.errors.aiDidNotUnderstand')
      
      // 添加AI回复到聊天记录
      const aiMessage: ChatMessage = {
        id: Date.now().toString() + '_ai',
        type: 'ai',
        content: aiResponse,
        timestamp: Date.now(),
        avatar: aiAvatar
      }
      setMessages(prev => [...prev, aiMessage])
      
      console.log('AI回复已添加到聊天记录:', aiResponse)
      
      // 自动滚动到最新消息
      setTimeout(scrollToBottom, 100)
      
      // 自动播报AI回复
      if (autoVoiceReply) {
        textToSpeech(aiResponse)
      } else {
        // 如果不自动播报，重置动画状态
        setAnimationState(prev => ({
          ...prev,
          isThinking: false,
          isIdle: true,
          emotion: 'happy'
        }))
      }
      
    } catch (error) {
      console.error('生成AI回复失败:', error)
      
      // 重置动画状态
      setAnimationState(prev => ({
        ...prev,
        isThinking: false,
        isIdle: true,
        emotion: 'neutral'
      }))
      
      // 根据错误类型提供更具体的错误信息
      let errorMessage = i18nT('tupi3.errors.aiServiceIssueTryLater')
      const errorStr = String(error)
      
      if (errorStr.includes('10004')) {
        errorMessage = i18nT('tupi3.errors.invalidMessageFormat')
      } else if (errorStr.includes('11200')) {
        errorMessage = i18nT('tupi3.errors.aiAuthFailed')
      } else if (errorStr.includes('网络')) {
        errorMessage = i18nT('tupi3.errors.networkIssue')
      } else if (errorStr.includes('WebSocket')) {
        errorMessage = i18nT('tupi3.errors.serverConnectionFailed')
      }
      
      const aiMessage: ChatMessage = {
        id: Date.now().toString() + '_ai',
        type: 'ai',
        content: errorMessage,
        timestamp: Date.now(),
        avatar: aiAvatar
      }
      setMessages(prev => [...prev, aiMessage])
      
      // 显示错误提示
      message.error(`${i18nT('tupi3.errors.aiReplyFailed')}: ${errorMessage}`)
      
      // 自动播报错误消息
      if (autoVoiceReply) {
        textToSpeech(errorMessage)
      }
    }
  }

  // 手动播放消息语音
  const playMessageVoice = (content: string) => {
    textToSpeech(content)
  }

  // 点击处理 - 点击头像切换语音识别状态
  const handleClick = () => {
    // 停止当前播放的音频
    stopPlaying()
    
    // 显示聊天框
    setChatBoxShown(true)
    
    // 切换语音识别状态
    if (isRecognizing) {
      // 当前正在识别，停止识别
      stopVoiceRecognition()
    } else {
      // 当前未识别，开始识别
      // 使用setTimeout确保UI更新后再启动识别，提供更好的用户体验
      setTimeout(() => {
        startVoiceRecognition()
      }, 50)
    }
  }

  // 获取头像样式（根据动画状态）
  const getAvatarStyle = () => {
    let borderColor = '#d9d9d9'
    let animation = 'none'
    
    if (animationState.isListening) {
      borderColor = '#ff4d4f'
      animation = 'pulse 1s infinite, listening-glow 2s infinite'
    } else if (animationState.isSpeaking) {
      borderColor = '#52c41a'
      animation = 'pulse 1.5s infinite, speaking-wave 1s infinite'
    } else if (animationState.isThinking) {
      borderColor = '#1890ff'
      animation = 'thinking-rotate 2s infinite'
    } else if (animationState.emotion === 'happy') {
      borderColor = '#faad14'
      animation = 'happy-bounce 2s infinite'
    }
    
    return {
      width: '100px',
      height: '100px',
      cursor: 'pointer',
      borderRadius: '50%',
      transition: 'all 0.3s ease',
      border: `3px solid ${borderColor}`,
      animation: animation,
      filter: animationState.isSpeaking ? 'brightness(1.1)' : 'none',
      transform: animationState.headMovement ? 'scale(1)' : 'scale(0.95)'
    }
  }

  return (
    <div style={{ position: 'relative' }}>
      {/* 瑶瑶头像 - 点击唤醒 */}
      <div style={{ position: 'relative' }}>
        <img
          src={img1}
          alt={i18nT('tupi3.avatar.alt.xiaowei')}
          style={{
            ...getAvatarStyle(),
            // 语音识别状态的视觉变化
            border: isRecognizing ? '3px solid #ff4d4f' : '3px solid transparent',
            borderRadius: '50%',
            transform: isRecognizing 
              ? 'scale(1.1)' 
              : (animationState.headMovement ? 'scale(1)' : 'scale(0.95)'),
            boxShadow: isRecognizing 
              ? '0 0 20px rgba(255, 77, 79, 0.6), 0 0 40px rgba(255, 77, 79, 0.3)' 
              : 'none',
            filter: isRecognizing 
              ? 'brightness(1.2) saturate(1.3)' 
              : (animationState.isSpeaking ? 'brightness(1.1)' : 'none'),
            transition: 'all 0.3s ease-in-out',
            cursor: 'pointer'
          }}
          onClick={handleClick}
          title={isRecognizing ? i18nT('tupi3.ui.clickToStop') : i18nT('tupi3.ui.clickToStart')}
        />
        
        {/* 状态指示器 */}
        <div style={{
          position: 'absolute',
          top: '-5px',
          right: '-5px',
          display: 'flex',
          flexDirection: 'column',
          gap: '2px'
        }}>
          {isRecognizing && (
            <Badge 
              count={i18nT('tupi3.ui.recording')} 
              style={{ 
                backgroundColor: '#ff4d4f', 
                fontSize: '8px',
                animation: 'pulse 1s infinite'
              }} 
            />
          )}
          {isSynthesizing && (
            <Badge count={i18nT('tupi3.ui.synthesizing')} style={{ backgroundColor: '#1890ff', fontSize: '8px' }} />
          )}
          {animationState.isThinking && (
            <Badge count={i18nT('tupi3.ui.thinking')} style={{ backgroundColor: '#722ed1', fontSize: '8px' }} />
          )}
        </div>
        
        {/* 语音识别实时反馈 */}
        {isRecognizing && (
          <div style={{
            position: 'absolute',
            bottom: '-60px',
            left: '50%',
            transform: 'translateX(-50%)',
            background: 'rgba(0, 0, 0, 0.8)',
            borderRadius: '20px',
            padding: '8px 16px',
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            minWidth: '200px',
            zIndex: 1000
          }}>
            {/* 音量指示器 */}
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}>
              {[...Array(5)].map((_, i) => (
                <div
                  key={i}
                  style={{
                    width: '3px',
                    height: `${8 + i * 4}px`,
                    backgroundColor: currentAudioData && currentAudioData.length > 0 
                      ? (i < Math.floor((currentAudioData.reduce((sum, val) => sum + Math.abs(val), 0) / currentAudioData.length) * 50)) 
                        ? '#52c41a' 
                        : 'rgba(255, 255, 255, 0.3)'
                      : 'rgba(255, 255, 255, 0.3)',
                    borderRadius: '2px',
                    animation: isRecognizing ? `voice-bar-${i} 0.5s ease-in-out infinite alternate` : 'none'
                  }}
                />
              ))}
            </div>
            
            {/* 识别状态文字 */}
            <span style={{ 
              color: 'white', 
              fontSize: '12px',
              fontWeight: 'bold'
            }}>
              {recognizedText || i18nT('tupi3.header.status.listening')}
            </span>
          </div>
        )}
        <Button
          type="text"
          icon={<SettingOutlined />}
          size="small"
          onClick={(e) => {
            e.stopPropagation()
            setShowControlPanel(!showControlPanel)
          }}
          style={{
            position: 'absolute',
            bottom: '-10px',
            right: '-10px',
            borderRadius: '50%',
            width: '24px',
            height: '24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#fff',
            boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
          }}
          title={i18nT('tupi3.ui.openControlPanel')}
        />
      </div>

      {/* 动画控制面板 */}
      {showControlPanel && (
        <div style={{
          position: 'absolute',
          top: '120px',
          left: '50%',
          transform: 'translateX(-50%)',
          width: '320px',
          backgroundColor: '#fff',
          borderRadius: '12px',
          boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
          border: '1px solid #e0e0e0',
          zIndex: 9998,
          padding: '16px'
        }}>
          <div style={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center',
            marginBottom: '16px'
          }}>
            <h4 style={{ margin: 0, fontSize: '14px', fontWeight: 'bold' }}>
              {i18nT('tupi3.panel.title')}
            </h4>
            <Button 
              type="text" 
              size="small"
              onClick={() => setShowControlPanel(false)}
            >
              ✕
            </Button>
          </div>
          
          <Tabs size="small" items={[
            {
              key: 'animation',
              label: i18nT('tupi3.panel.tabs.animation'),
              children: (
                <div style={{ fontSize: '12px' }}>
                  <div style={{ marginBottom: '12px' }}>
                    <label>{i18nT('tupi3.panel.labels.emotion')}</label>
                    <div style={{ display: 'flex', gap: '8px', marginTop: '4px' }}>
                      {[
                        { key: 'neutral', icon: '😐' },
                        { key: 'happy', icon: '😊' },
                        { key: 'excited', icon: '🤩' },
                        { key: 'focused', icon: '🤔' }
                      ].map(emotion => (
                        <Button
                          key={emotion.key}
                          size="small"
                          type={animationState.emotion === emotion.key ? 'primary' : 'default'}
                          onClick={() => setAnimationState(prev => ({ ...prev, emotion: emotion.key as any }))}
                          style={{ fontSize: '10px', padding: '2px 6px' }}
                        >
                          {emotion.icon} {i18nT(`tupi3.emotions.${emotion.key}`)}
                        </Button>
                      ))}
                    </div>
                  </div>
                  
                  <div style={{ marginBottom: '12px' }}>
                    <label>{i18nT('tupi3.panel.labels.blinkRate')}</label>
                    <Slider
                      min={1}
                      max={10}
                      value={animationState.eyeBlinkRate}
                      onChange={(value) => setAnimationState(prev => ({ ...prev, eyeBlinkRate: value }))}
                      style={{ margin: '8px 0' }}
                    />
                  </div>
                  
                  <div>
                    <Switch
                      checked={animationState.headMovement}
                      onChange={(checked) => setAnimationState(prev => ({ ...prev, headMovement: checked }))}
                      size="small"
                    />
                    <span style={{ marginLeft: '8px' }}>{i18nT('tupi3.panel.labels.headMovement')}</span>
                  </div>
                </div>
              )
            },
            {
              key: 'voice',
              label: i18nT('tupi3.panel.tabs.voice'),
              children: (
                <div style={{ fontSize: '12px' }}>
                  <div style={{ marginBottom: '12px' }}>
                    <label>{i18nT('tupi3.panel.labels.volume')} {voiceVolume}</label>
                    <Slider
                      min={0}
                      max={100}
                      value={voiceVolume}
                      onChange={setVoiceVolume}
                      style={{ margin: '8px 0' }}
                    />
                  </div>
                  
                  <div style={{ marginBottom: '12px' }}>
                    <label>{i18nT('tupi3.panel.labels.speed')} {voiceSpeed}</label>
                    <Slider
                      min={0}
                      max={100}
                      value={voiceSpeed}
                      onChange={setVoiceSpeed}
                      style={{ margin: '8px 0' }}
                    />
                  </div>
                  
                  <div style={{ marginBottom: '12px' }}>
                    <label>{i18nT('tupi3.panel.labels.pitch')} {voicePitch}</label>
                    <Slider
                      min={0}
                      max={100}
                      value={voicePitch}
                      onChange={setVoicePitch}
                      style={{ margin: '8px 0' }}
                    />
                  </div>
                  
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                    <div>
                      <Switch
                        checked={autoVoiceReply}
                        onChange={setAutoVoiceReply}
                        size="small"
                      />
                      <span style={{ marginLeft: '8px' }}>{i18nT('tupi3.panel.labels.autoReply')}</span>
                    </div>
                    
                    <div style={{ marginTop: '12px' }}>
                      <label>{i18nT('tupi3.panel.labels.timeout')} {voiceTimeout}ms</label>
                      <Slider
                        min={1000}
                        max={10000}
                        step={500}
                        value={voiceTimeout}
                        onChange={setVoiceTimeout}
                        style={{ margin: '8px 0' }}
                        tooltip={{ formatter: (value) => `${value}ms` }}
                      />
                    </div>
                    
                    <div>
                      <Switch
                        checked={continuousListening}
                        onChange={setContinuousListening}
                        size="small"
                      />
                      <span style={{ marginLeft: '8px' }}>{i18nT('tupi3.panel.labels.continuousListening')}</span>
                    </div>
                    
                    <div>
                      <Switch
                        checked={showVoicePanel}
                        onChange={setShowVoicePanel}
                        size="small"
                      />
                      <span style={{ marginLeft: '8px' }}>{i18nT('tupi3.panel.labels.recognitionPanel')}</span>
                    </div>
                    
                    <div>
                      <Switch
                        checked={showTestPanel}
                        onChange={setShowTestPanel}
                        size="small"
                      />
                      <span style={{ marginLeft: '8px' }}>{i18nT('tupi3.panel.labels.performancePanel')}</span>
                    </div>
                    
                    <div>
                      <Switch
                        checked={showTTSDebugger}
                        onChange={setShowTTSDebugger}
                        size="small"
                      />
                      <span style={{ marginLeft: '8px' }}>{i18nT('tupi3.panel.labels.ttsDebugger')}</span>
                    </div>
                  </div>
                </div>
              )
            },
            {
              key: 'test',
              label: (
                <span>
                  <ExperimentOutlined />
                  {i18nT('tupi3.performance.title')}
                </span>
              ),
              children: (
                <div style={{ fontSize: '12px' }}>
                  <div style={{ marginBottom: '12px', color: '#666' }}>
                    {i18nT('tupi3.performance.desc')}
                  </div>
                  
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                    <Button 
                      type="primary" 
                      size="small"
                      icon={<ExperimentOutlined />}
                      onClick={() => setShowTestPanel(true)}
                      style={{ width: '100%' }}
                    >
                      {i18nT('tupi3.performance.openPanel')}
                    </Button>
                    
                    <div style={{ fontSize: '11px', color: '#999', textAlign: 'center' }}>
                      {i18nT('tupi3.performance.items')}
                    </div>
                  </div>
                </div>
              )
            }
          ]} />
        </div>
      )}

      {/* 对话框 - 优化UI布局 */}
      {chatBoxShown && (
        <div style={{
          position: 'absolute',
          top: '-420px',
          left: '50%',
          transform: 'translateX(-50%)',
          width: '380px',
          height: '400px',
          backgroundColor: '#fff',
          borderRadius: '16px',
          boxShadow: '0 12px 32px rgba(0,0,0,0.15)',
          border: '1px solid #e0e0e0',
          zIndex: 9999,
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden'
        }}>
          {/* 对话框头部 - 优化设计 */}
          <div style={{
            padding: '16px 20px',
            borderBottom: '1px solid #f0f0f0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            color: '#fff'
          }}>
            <div style={{ 
              display: 'flex',
              alignItems: 'center',
              gap: '12px'
            }}>
              <div style={{
                width: '32px',
                height: '32px',
                borderRadius: '50%',
                overflow: 'hidden',
                border: '2px solid rgba(255,255,255,0.3)'
              }}>
                <img 
                  src={aiAvatar} 
                  alt={i18nT('tupi3.avatar.alt.xiaowei')} 
                  style={{ 
                    width: '100%', 
                    height: '100%', 
                    objectFit: 'cover' 
                  }} 
                />
              </div>
              <div>
                <div style={{ 
                  fontSize: '16px', 
                  fontWeight: 'bold'
                }}>
                  {i18nT('tupi3.header.title')}
                </div>
                <div style={{ 
                  fontSize: '12px', 
                  opacity: 0.8
                }}>
                  {animationState.isListening ? i18nT('tupi3.header.status.listening') : 
                   animationState.isSpeaking ? i18nT('tupi3.header.status.speaking') :
                   animationState.isThinking ? i18nT('tupi3.header.status.thinking') : i18nT('tupi3.header.status.online')}
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button
                type="text"
                icon={isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                onClick={() => isPlaying ? stopPlaying() : null}
                style={{ color: '#fff', border: 'none' }}
                size="small"
                title={isPlaying ? i18nT('tupi3.ui.stopPlaying') : i18nT('tupi3.ui.playingStatus')}
              />
              <Button
                type="text"
                onClick={() => {
                  setChatBoxShown(false)
                  if (isRecognizing) {
                    stopVoiceRecognition()
                  }
                  if (isPlaying) {
                    stopPlaying()
                  }
                }}
                style={{ color: '#fff', border: 'none' }}
                size="small"
              >
                ✕
              </Button>
            </div>
          </div>

          {/* 聊天消息区域 - 优化布局 */}
          <div className="chat-messages" style={{
            flex: 1,
            padding: '16px',
            backgroundColor: '#f8f9fa',
            overflowY: 'auto',
            display: 'flex',
            flexDirection: 'column',
            gap: '16px',
            backgroundImage: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
          }}>
            {messages.length === 0 ? (
              <div style={{
                textAlign: 'center',
                color: '#6c757d',
                fontSize: '14px',
                padding: '40px 20px',
                background: 'rgba(255,255,255,0.9)',
                borderRadius: '16px',
                border: '2px dashed #dee2e6'
              }}>
                <div style={{ fontSize: '32px', marginBottom: '12px' }}>🎙️</div>
                <div style={{ fontWeight: 'bold', marginBottom: '8px' }}>{i18nT('tupi3.chat.empty.title')}</div>
                <div style={{ fontSize: '12px', color: '#adb5bd' }}>
                  {i18nT('tupi3.chat.empty.hint')}
                </div>
              </div>
            ) : (
              messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`message-container ${
                    msg.type === 'voice-recognition' ? 'voice-recognition-message' + 
                    (msg.isRealtime ? ' realtime' : '') :
                    msg.type === 'ai' ? 'ai-message' : 'user-message'
                  }`}
                  style={{
                    display: 'flex',
                    alignItems: 'flex-start',
                    justifyContent: msg.type === 'user' || msg.type === 'voice-recognition' ? 'flex-end' : 'flex-start',
                    gap: '12px',
                    opacity: msg.isRealtime ? 0.8 : 1,
                    transform: msg.isRealtime ? 'scale(0.98)' : 'scale(1)',
                    transition: 'all 0.3s ease-in-out'
                  }}
                >
                  {/* AI头像 - 左侧 */}
                  {msg.type === 'ai' && (
                    <div style={{
                      width: '36px',
                      height: '36px',
                      borderRadius: '50%',
                      overflow: 'hidden',
                      flexShrink: 0,
                      border: '2px solid #52c41a',
                      boxShadow: '0 2px 8px rgba(82, 196, 26, 0.3)'
                    }}>
                      <img 
                        src={msg.avatar || aiAvatar} 
                        alt={i18nT('tupi3.avatar.alt.assistant')} 
                        style={{ 
                          width: '100%', 
                          height: '100%', 
                          objectFit: 'cover' 
                        }} 
                      />
                    </div>
                  )}
                  
                  {/* 消息内容 - 优化样式 */}
                  <div style={{
                    maxWidth: '75%',
                    position: 'relative'
                  }}>
                    <div style={{
                      padding: '12px 16px',
                      borderRadius: msg.type === 'user' || msg.type === 'voice-recognition' ? '20px 20px 6px 20px' : '20px 20px 20px 6px',
                      backgroundColor: msg.type === 'user' ? 
                        'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : 
                        msg.type === 'voice-recognition' ? 
                        'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)' : '#fff',
                      color: msg.type === 'user' || msg.type === 'voice-recognition' ? '#fff' : '#333',
                      fontSize: '14px',
                      lineHeight: '1.6',
                      wordBreak: 'break-word',
                      border: msg.type === 'ai' ? '1px solid #e0e0e0' : 
                             msg.type === 'voice-recognition' ? '2px dashed rgba(255, 255, 255, 0.5)' : 'none',
                      boxShadow: msg.type === 'user' ? 
                        '0 4px 12px rgba(102, 126, 234, 0.3)' : 
                        msg.type === 'voice-recognition' ?
                        '0 4px 12px rgba(255, 154, 158, 0.3)' :
                        '0 4px 12px rgba(0, 0, 0, 0.1)',
                      background: msg.type === 'user' ? 
                        'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : 
                        msg.type === 'voice-recognition' ?
                        'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)' : '#fff',
                      position: 'relative'
                    }}>
                      {/* 语音识别标识 */}
                      {msg.type === 'voice-recognition' && (
                        <div className="voice-recognition-badge" style={{
                          position: 'absolute',
                          top: '-8px',
                          left: '12px',
                          backgroundColor: '#ff6b6b',
                          color: '#fff',
                          fontSize: '10px',
                          padding: '2px 6px',
                          borderRadius: '8px',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px',
                          boxShadow: '0 2px 4px rgba(255, 107, 107, 0.3)'
                        }}>
                          <AudioOutlined style={{ fontSize: '8px' }} />
                          {msg.isRealtime ? (
                            <span>
                              {i18nT('tupi3.ui.recognizing')}<span className="realtime-dots">...</span>
                            </span>
                          ) : i18nT('tupi3.ui.recognized')}
                        </div>
                      )}
                      
                      {msg.content}
                      
                      {/* 实时识别动画效果 */}
                      {msg.type === 'voice-recognition' && msg.isRealtime && (
                        <div style={{
                          position: 'absolute',
                          bottom: '8px',
                          right: '12px',
                          display: 'flex',
                          gap: '2px'
                        }}>
                          {[0, 1, 2].map(i => (
                            <div
                              key={i}
                              style={{
                                width: '4px',
                                height: '4px',
                                borderRadius: '50%',
                                backgroundColor: 'rgba(255, 255, 255, 0.8)',
                                animation: `pulse 1.4s ease-in-out ${i * 0.2}s infinite`
                              }}
                            />
                          ))}
                        </div>
                      )}
                      
                      {/* 消息操作按钮 */}
                      {msg.type === 'ai' && (
                        <Button
                          type="text"
                          icon={<SoundOutlined />}
                          size="small"
                          onClick={() => playMessageVoice(msg.content)}
                          style={{
                            position: 'absolute',
                            top: '-8px',
                            right: '-8px',
                            borderRadius: '50%',
                            width: '24px',
                            height: '24px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            backgroundColor: '#fff',
                            boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                            fontSize: '10px'
                          }}
                          title={i18nT('tupi3.ui.playVoice')}
                        />
                      )}
                    </div>
                    
                    {/* 时间戳 */}
                    <div style={{
                      fontSize: '10px',
                      color: msg.type === 'user' || msg.type === 'voice-recognition' ? 'rgba(255,255,255,0.7)' : '#999',
                      marginTop: '4px',
                      textAlign: 'right'
                    }}>
                      {new Date(msg.timestamp).toLocaleTimeString()}
                    </div>
                  </div>
                  
                  {/* 用户头像 - 右侧 */}
                  {(msg.type === 'user' || msg.type === 'voice-recognition') && (
                    <div style={{
                      width: '36px',
                      height: '36px',
                      borderRadius: '50%',
                      overflow: 'hidden',
                      flexShrink: 0,
                      border: msg.type === 'voice-recognition' ? '2px solid #ff6b6b' : '2px solid #667eea',
                      boxShadow: msg.type === 'voice-recognition' ? 
                        '0 2px 8px rgba(255, 107, 107, 0.3)' : 
                        '0 2px 8px rgba(102, 126, 234, 0.3)'
                    }}>
                      <img 
                        src={msg.avatar || userAvatar} 
                        alt={i18nT('tupi3.avatar.alt.user')} 
                        style={{ 
                          width: '100%', 
                          height: '100%', 
                          objectFit: 'cover' 
                        }} 
                      />
                    </div>
                  )}
                </div>
              ))
            )}
            
            {/* 消息滚动锚点 */}
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 */}
          <div style={{
            padding: '16px',
            borderTop: '1px solid #f0f0f0',
            backgroundColor: '#fff'
          }}>
            {/* 语音识别结果现在直接显示在聊天消息区域，不再在输入区域显示 */}
            
            <div style={{ display: 'flex', gap: '12px', alignItems: 'flex-end' }}>
              <Input.TextArea
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                placeholder={i18nT('tupi3.input.placeholder')}
                autoSize={{ minRows: 1, maxRows: 4 }}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault()
                    sendMessage()
                  }
                }}
                style={{
                  flex: 1,
                  resize: 'none'
                }}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={() => sendMessage()}
                disabled={!inputText.trim()}
                style={{
                  height: '32px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                {i18nT('tupi3.input.send')}
              </Button>
            </div>
          </div>
        </div>
      )}
      
      {/* 隐藏的音频元素 */}
      <audio
        ref={audioRef}
        onLoadedData={() => {
          // 音频加载完成后连接到分析器
          if (audioRef.current) {
            globalAudioAnalyzer.connectAudio(audioRef.current)
            
            // 设置音频数据回调
            const handleAudioData = (data: any) => {
              setAudioData(data)
            }
            
            globalAudioAnalyzer.onAnalysisData(handleAudioData)
          }
        }}
        onPlay={() => {
          console.log('音频开始播放')
          setIsPlaying(true)
          setPlaying(true) // 更新全局播放状态
        }}
        onEnded={() => {
          setIsPlaying(false)
          setPlaying(false) // 更新全局播放状态
          // 播放结束后重置动画状态
          setAnimationState(prev => ({
            ...prev,
            isSpeaking: false,
            isIdle: true,
            emotion: 'happy'
          }))
          // 重置全局语音状态
          setSpeaking(false)
          setCurrentText('')
          setAudioData(null)
          
          // 停止音频分析
          globalAudioAnalyzer.stopAnalysis()
        }}
        onError={() => {
          setIsPlaying(false)
          setPlaying(false) // 更新全局播放状态
          setAnimationState(prev => ({
            ...prev,
            isSpeaking: false,
            isIdle: true,
            emotion: 'neutral'
          }))
          // 重置全局语音状态
          setSpeaking(false)
          setCurrentText('')
    message.error(i18nT('tupi3.errors.audioPlayFailed'))
        }}
      />
      
      {/* 语音识别面板 */}
      {showVoicePanel && (
        <VoiceRecognitionPanel
          isRecognizing={isRecognizing}
          recognizedText={recognizedText}
          audioData={currentAudioData}
          stats={voiceStats}
          onStartRecognition={startVoiceRecognition}
          onStopRecognition={stopVoiceRecognition}
          style={{
            position: 'absolute',
            top: '-480px',
            left: '50%',
            transform: 'translateX(-50%)',
            zIndex: 10000
          }}
        />
      )}
      
      {/* 性能测试面板 */}
      {showTestPanel && (
        <TestRunner
          onClose={() => setShowTestPanel(false)}
          style={{
            position: 'absolute',
            top: '-600px',
            left: '50%',
            transform: 'translateX(-50%)',
            zIndex: 10001
          }}
        />
      )}
      
      {/* TTS调试器 */}
      {showTTSDebugger && (
        <TTSDebugger
          style={{
            position: 'absolute',
            top: '-400px',
            right: '20px',
            zIndex: 10002
          }}
        />
      )}
      
      {/* CSS动画 */}
      <style>
        {`
          @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
          }
          
          @keyframes listening-glow {
            0% { box-shadow: 0 0 5px #ff4d4f; }
            50% { box-shadow: 0 0 20px #ff4d4f, 0 0 30px #ff4d4f; }
            100% { box-shadow: 0 0 5px #ff4d4f; }
          }
          
          @keyframes speaking-wave {
            0% { box-shadow: 0 0 5px #52c41a; }
            25% { box-shadow: 0 0 10px #52c41a, 0 0 15px #52c41a; }
            50% { box-shadow: 0 0 20px #52c41a, 0 0 25px #52c41a; }
            75% { box-shadow: 0 0 10px #52c41a, 0 0 15px #52c41a; }
            100% { box-shadow: 0 0 5px #52c41a; }
          }
          
          @keyframes thinking-rotate {
            0% { transform: rotate(0deg); filter: hue-rotate(0deg); }
            100% { transform: rotate(360deg); filter: hue-rotate(360deg); }
          }
          
          @keyframes happy-bounce {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-5px); }
          }
          
          /* 语音识别音量条动画 */
          @keyframes voice-bar-0 {
            0% { height: 8px; }
            100% { height: 12px; }
          }
          
          @keyframes voice-bar-1 {
            0% { height: 12px; }
            100% { height: 18px; }
          }
          
          @keyframes voice-bar-2 {
            0% { height: 16px; }
            100% { height: 24px; }
          }
          
          @keyframes voice-bar-3 {
            0% { height: 20px; }
            100% { height: 28px; }
          }
          
          @keyframes voice-bar-4 {
            0% { height: 24px; }
            100% { height: 32px; }
          }
        `}
      </style>
    </div>
  )
}

export default Tupi3